//
//  ViewController.swift
//  UseCoreData
//
//  Created by liy on 2025/1/19.
//

import CoreData
import UIKit

class ViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()

    let ctx = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    let row = NSEntityDescription.insertNewObject(forEntityName: "User", into: ctx)
    row.setValue("baobao", forKey: "name")
    row.setValue(1, forKey: "age")
    row.setValue(true, forKey: "isMale")

    do {
      try ctx.save()
    } catch {
      print("\(error)")
    }
  }

  //	获取沙盒保存路径
  func getCoreDataStorePathUsingManagedObjectContext() -> String? {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
      return nil
    }
    let managedObjectContext = appDelegate.persistentContainer.viewContext
    guard let persistentStoreCoordinator = managedObjectContext.persistentStoreCoordinator else {
      return nil
    }
    guard let storeURL = persistentStoreCoordinator.persistentStores.first?.url else {
      return nil
    }
    return storeURL.path
  }
}
